<template>
    <div class="h-full overflow-hidden flex flex-col">
        <div class="flex-1 overflow-auto pt-[26px] pb-[80px] px-[56px]">
            <div class="flex flex-row items-center gap-[10px]">
                <div class="bg-theme w-1 h-5 rounded-xs"></div>
                <span class="text-theme text-[18px] font-bold">公司视频</span>
            </div>
            <section class="bg-[#F5F7FA] rounded-sm box-border p-4 mt-3 2xl:w-[750px]">
                <p class="text-sm text-primary">上传公司视频有什么用？</p>
                <p class="text-sm text-secondary mt-2">大气的公司宣传视频加深牛人对公司的印象;完整的公司环境视频增强牛人沉浸感，丰富的团建视频让牛人对公司更感兴趣；企业宣传片、环境介绍、产品介绍、活动记录等均可上传。(最多可上传5个视频)</p>
            </section>
            <section class="mt-6 2xl:w-[750px]">
                <div class="flex flex-row items-center gap-[10px]">
                    <a-button @click="triggerToAction(TriggerAction.Create, null)" type="primary" ghost size="large" style="width: 128px; display: flex; align-items: center; justify-content: center;">
                        <template #icon>
                            <GpFontIcon name="icon-tianjiashipin" class="!text-xl" />
                        </template>
                        添加视频
                    </a-button>
                    <div class="text-third text-sm flex flex-row items-center gap-1 cursor-pointer">
                        上传注意事项
                        <GpFontIcon name="icon-yiwen1" class="text-[#ACAEB2]"/>
                    </div>
                </div>
                <p class="mt-[10px] text-third text-sm">
                    <span class="text-[#FC474C]">* </span>支持内容时长为最短10秒，最长10分钟；文件最大为【300 M】；最多可上传5个视频哦
                </p>
                <div class="mt-6">
                    <div class="flex flex-row justify-between items-center">
                        <h5 class="text-primary text-base font-medium">视频列表</h5>
                        <div class="flex flex-row items-center justify-center box-border p-1 rounded-sm bg-[#F5F7FA]">
                            <div :class="['filter-item', !publishState && 'current']" @click="publishState = false">待发布({{countInfo.pending}})</div>
                            <div :class="['filter-item', publishState && 'current']" @click="publishState = true">已发布({{countInfo.published}})</div>
                        </div>
                    </div>
                    <ul class="box-border" v-if="list.length > 0">
                        <li class="mt-3 pl-3 pr-8 rounded-sm border border-solid border-[#E8EBF5] w-full flex flex-row items-center"
                            style="height: 137px;"
                            v-for="item of list" :key="item.id"
                        >
                            <div class="relative cursor-pointer overflow-hidden w-[200px] h-[113px] rounded-sm flex-none" @click="handlePlayVideo(item)">
                                <img :src="item.coverImg" width="100%" height="100%" class="size-full object-cover" />
                                <div class="absolute inset-0 bg-black/40 flex justify-center items-center">
                                    <GpFontIcon name="icon-bofang" class="!text-[32px] text-white" />
                                    <span class="absolute text-white text-xs bottom-[6px] right-[6px]">
                                        {{ item.videoTime ? item.duration : '--' }}
                                    </span>
                                </div>
                            </div>
                            <div class="flex flex-col gap-9 ml-4 flex-1 w-0">
                                <p class="text-base text-primary font-medium">{{ item.title }}</p>
                                <div class="flex flex-row gap-[50px] items-center text-third">
                                    <!-- <a-flex :gap="8" align="center">
                                        <GpFontIcon name="icon-bofangjilu" />
                                        <span class="text-sm">5689</span>
                                    </a-flex> -->
                                    <a-flex :gap="8" align="center">
                                        <GpFontIcon name="icon-shangchuanshijian" />
                                        <span class="text-sm">{{ item.addTime ? dateFormat(item.addTime, 'short') : '--' }}</span>
                                    </a-flex>
                                </div>
                            </div>
                            <div class="float-none">
                                <a-flex align="center" :gap="32">
                                    <span class="text-sm text-theme touchable-opacity" @click="triggerToAction(TriggerAction.Update, item)">编辑</span>
                                    <span class="text-sm text-[#F34C4C] touchable-opacity" @click="handleDel(item)">删除</span>
                                </a-flex>
                            </div>
                        </li>
                    </ul>
                    <GpEmpty v-else
                        src="/images/empty-novideo.png"
                        description="暂无内容，快去添加吧~"
                        img-class="w-[150px] h-[130px]"
                        class="mt-16"
                    />
                </div>
            </section>
        </div>
        <a-modal v-model:open="open"
            v-bind="defaultModalProps"
            :title="triggerAction === TriggerAction.Create ? '添加视频' : '更新视频'"
            :width="612"
            :body-style="{paddingBlockStart: '26px', paddingBlockEnd: '56px'}"
            :confirm-loading="uploading || submiting"
            @cancel="handleCancel()"
            @ok="handleConfirm()"
        >
            <div class="box-border">
                <div class="flex flex-row items-start gap-3 mb-8">
                    <label class="text-sm text-secondary flex-none">上传视频</label>
                    <div>
                        <p class="text-sm text-third">
                            <span class="text-[#FC474C]">* </span>支持内容时长为<span class="text-theme">最短10秒</span>，<span class="text-theme">最长10分钟</span>；文件<span class="text-theme">最大为【300 M】</span>
                        </p>
                        <div @click="triggerUpload()" style="width: 200px; height: 113px;" :class="uploading ? 'cursor-not-allowed' : 'cursor-pointer'"
                           class="relative mt-4 rounded-sm overflow-hidden border border-dashed border-[#CED4DB] hover:border-theme bg-[#FCFBFF]">
                            <div class="size-full flex flex-col justify-center items-center">
                                <GpFontIcon name="icon-shangchuan" class="!text-[40px] !leading-none text-[#ced4db]" />
                                <span class="text-sm text-[#ACAEB2]">上传视频</span>
                            </div>
                            <div class="absolute inset-0 group" v-if="actionState.video">
                                <img :src="actionState.coverImg" width="100%" height="100%" class="size-full object-cover"/>
                                <div class="absolute inset-0 bg-black/60 hidden group-hover:flex flex-col justify-center items-center text-white">
                                    <GpFontIcon name="icon-zhongxinshangchuan" class="!text-[40px] !leading-none" />
                                    <span class="text-sm mt-[2px]">重新上传</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="flex flex-row items-center gap-3 mb-8">
                    <label class="text-sm text-secondary flex-none">视频标题</label>
                    <a-input v-model:value="actionState.title" size="large" placeholder="请输入标题" style="width: 100%;" />
                </div>
                <div class="flex flex-row items-center gap-3">
                    <label class="text-sm text-secondary flex-none">是否发布</label>
                    <a-switch v-model:checked="actionState.isPublish" />
                </div>
            </div>
        </a-modal>
    </div>
</template>
<script lang="ts" setup>
import { defaultModalProps } from '@/constants/comp-setting';
import type { CompanyInfoResult, CompanyVideoRequest } from '@/api/siderBar/model';
import { dateFormat } from '@/utils/dayjs';
import { formatDuration } from '@/utils/app';
import { message, Modal } from 'ant-design-vue';
import { useAppStore } from '@/stores';
import { postCompanyinfoDelvideo, postCompanyinfoEditvideo, putCompanyinfoAddvideo } from '@/api/siderBar/companyInfo';

defineOptions({
    name: "CompanyVideo"
})
type VideoItem = CompanyVideoRequest & {
    /** @frontend */
    duration?: string
}
enum TriggerAction {
    Create,
    Update
}
type Props = Partial<CompanyInfoResult>
const props = defineProps<Props>()
const emit = defineEmits<{
    refresh: []
}>()
const appStore = useAppStore()
const publishState = ref(true)
const list = computed<VideoItem[]>(() => {
    if (props.videos && props.videos.length > 0) {
        const isPublish = publishState.value
        const _list: VideoItem[] =  props.videos.filter(l => Boolean(l.isPublish) === isPublish)
        _list.forEach(l => {
            if (l.videoTime) {
                const { hours, minutes, seconds } = formatDuration(l.videoTime)
                const parts = [minutes, seconds]
                if (hours) {
                    parts.unshift(hours)
                }
                l.duration = parts.map(part => String(part).padStart(2, '0')).join(":")
            }
        })
        return _list
    }
    return []
})
const countInfo = computed(() => {
    let published = 0;
    let pending = 0;
    if (props.videos && props.videos.length > 0) {
        props.videos.forEach(l => {
            if (l.isPublish) {
                published++
            } else {
                pending++
            }
        })
    }
    return {
        published,
        pending
    }
})
const open = ref(false)
const submiting = ref(false)
const triggerAction = ref<TriggerAction>(TriggerAction.Create)
const actionState = ref(getInitialState())
const { uploadAction, uploading } = useUpload({
    beforeUpload([file]) {
        if (!sizeLimit(file.size, 300)) {
            message.warn('文件最大为【300 M】')
            return false
        }
    },
    receiveResults([video]) {
        if (video) {
            const { fullName, videoCoverImg, videoDuration } = video
            actionState.value.video = fullName
            actionState.value.coverImg = videoCoverImg!
            actionState.value.videoTime = videoDuration!
        }
    },
    globalLoading: false,
    type: "video"
})
function triggerUpload() {
    if (props.videos && props.videos.length >= 5) {
        message.warn('最多可上传5个视频哦')
    } else {
        uploadAction()
    }
}
function getInitialState(): Partial<VideoItem> {
    return {
        isPublish: false
    }
}
function handleCancel() {
    submiting.value = false
    open.value = false
    triggerAction.value = TriggerAction.Create
    actionState.value = getInitialState()
}
async function handleConfirm() {
    const { duration, ...rest } = actionState.value
    if (!rest.video) {
        message.error('请上传视频')
        return
    }
    if (!rest.title || rest.title.trim().length === 0) {
        message.error('请输入视频标题')
        return
    }
    submiting.value = true
    try {
        if (triggerAction.value === TriggerAction.Update) {
            await postCompanyinfoEditvideo(rest as CompanyVideoRequest)
            message.success('修改成功')
        } else {
            await putCompanyinfoAddvideo({
                ...rest,
                addTime: dateFormat(void 0, "long")
            } as CompanyVideoRequest)
            message.success('添加成功')
        }
        submiting.value = false
        handleCancel()
        emit('refresh')
    } catch (error) {
        submiting.value = false
    }
}
function triggerToAction<Action extends TriggerAction>(action: Action, item: Action extends TriggerAction.Update ? VideoItem : null) {
    triggerAction.value = action
    if (triggerAction.value === TriggerAction.Update && item) {
        actionState.value = { ...item }
    }
    open.value = true
}
function handleDel(item: VideoItem) {
    Modal.confirm({
        title: '确认提示',
        content: '确认要删除吗？',
        async onOk() {
            try {
                appStore.toggleLoading(true)
                await postCompanyinfoDelvideo({ id: item.id})
                appStore.toggleLoading(false)
                emit('refresh')
            } catch (error) {
                appStore.toggleLoading(false)
            }
        },
    })
}
function handlePlayVideo(item: VideoItem) {
    if (appStore.compRefs.VideoPreviewModalRef.value) {
        appStore.compRefs.VideoPreviewModalRef.value.open({
            url: item.video,
            autoplay: true
        })
    }
}
</script>
<style lang="less" scoped>
@reference "../../../../../../assets/styles/tailwind.css";
.filter-item {
    width: 90px;
    height: 32px;
    @apply rounded-sm cursor-pointer text-sm text-primary flex flex-row justify-center items-center;
    &.current {
        @apply bg-white font-bold text-theme;
    }
}
</style>